package com.lanswon.qzsmk.controller.cardManageController;

import java.io.File;
import java.io.IOException;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import ch.qos.logback.classic.Logger;

import com.lanswon.qzsmk.base.DwzPage;
import com.lanswon.qzsmk.base.HttpContants;
import com.lanswon.qzsmk.base.PathContants;
import com.lanswon.qzsmk.dao.BusinessMapper;
import com.lanswon.qzsmk.exception.ApplicationException;
import com.lanswon.qzsmk.service.cardManageService.ApplyCardService;
import com.lanswon.qzsmk.service.systemManageService.ParamManageService;
import com.lanswon.qzsmk.util.Excel;
import com.lanswon.qzsmk.vo.Other;
import com.lanswon.qzsmk.vo.ResultVo;
import com.lanswon.qzsmk.vo.ShowChargeVo;
import com.lanswon.qzsmk.vo.VoucherVo;

/**
 * 卡批量申请controller类
 * 
 * @author Guyw
 *
 */
@Controller
@RequestMapping(value = "/applicationBatch")
public class ApplicationBatchController {

	private final static Logger logger = (Logger) LoggerFactory.getLogger(ApplicationBatchController.class);

	@Autowired
	ApplyCardService acs;

	@Autowired
	ParamManageService pm;
	
	@Autowired
	BusinessMapper bm;

	@RequiresPermissions("applicationBatch:fileUploadIndex")
	@RequestMapping(value = "/goFileUpload", name = "跳转上传文件页面,applicationBatch:fileUploadIndex", method = {
			RequestMethod.GET, RequestMethod.POST })
	public String fileUploadIndex() {
		return "FileUpload";
	}

	@RequiresPermissions("applicationBatch:fileUpload")
	@ResponseBody
	@RequestMapping(name = "上传批量文件,applicationBatch:fileUpload", value = "/fileUpload", method = { RequestMethod.POST })
	public Map<String, Object> fileUpload(@RequestParam("files") MultipartFile[] files, HttpServletRequest request) throws IOException, ApplicationException {
		Map<String, Object> map = new HashMap<>();
		String root = request.getSession().getServletContext().getRealPath("/");

		map.put("navTabId", "ApplicationBatch");
		map.put("callbackType", "closeCurrent");
		map.put("forwardUrl", "applicationBatch/batch");// post请求
		

		
		String applyBatchFileName = "";
		
		//验证不含excel
		boolean  b = false;
		for(MultipartFile  mf:files){
			if(mf.getOriginalFilename().contains(".xlsx")){
				b = true;
				break;
			}
		}
		
		if(!b){
			map.put("statusCode", "300");
			map.put("message", "请选择excel导入");
			return map;//不包含excel
		}
			
		
		List<String> allApplyNos = acs.queryAllApplyNos();
		if (files != null && files.length > 0) {
			for (int i = 0; i < files.length; i++) {
				MultipartFile file = files[i];
				// 保存文件
					for(String imported:allApplyNos){
						if(file.getOriginalFilename().contains(imported)){
							map.put("statusCode", "300");
							map.put("message", "请勿重复导入批次文件【"+imported+"】");
							return map;
						}
					}
				
				
				


						if (file.getOriginalFilename().endsWith(".xlsx")) {
							logger.debug("上传的excel名:[{}]", file.getOriginalFilename());
							File ff = new File(root + PathContants.PROJECT_PATH_EXCEL);
							logger.debug("目录【{}】", ff.getAbsolutePath());
							if (!ff.exists()) {
								logger.debug("开始创建");
								ff.mkdirs();
							}
							File fi = new File(ff.getAbsolutePath() + File.separator + file.getOriginalFilename());
							if (fi.exists()) {
								map.put("statusCode", "300");
								map.put("message", "请勿重复上传批次文件【"+file.getOriginalFilename()+"】");
								return map;
							}
							
							//验证字段为空
							Excel.validExcel(file.getInputStream());

							file.transferTo(fi);

							applyBatchFileName = file.getOriginalFilename().substring(0,
									file.getOriginalFilename().indexOf("."));
						} else if (file.getOriginalFilename().endsWith("jpg")
								|| file.getOriginalFilename().endsWith("bmp")
								|| file.getOriginalFilename().endsWith("gif")
								|| file.getOriginalFilename().endsWith("png")) {
							logger.debug("上传的照片名:[{}]", file.getOriginalFilename());

							File ff = new File(root + PathContants.PROJECT_PATH_IMG + File.separator + applyBatchFileName);
							if (!ff.exists()) {
								ff.mkdirs();
							}
							File fi = new File(ff.getAbsolutePath() + File.separator + file.getOriginalFilename());
							if (!fi.exists()) {
								fi.createNewFile();
							}

							file.transferTo(fi);

						}else{
							map.put("statusCode", "300");
							map.put("message", "文件包含了其他格式");
							return map;
						}
						

				}
			}else {
				// 提示 没有选择文件
				map.put("statusCode", "300");
				map.put("message", "请选择文件上传");
				
				return map;
			}
		map.put("statusCode", "200");
		map.put("message", "操作成功");
		
		
		return map;
	}

	/**
	 * 批量申请跳转页面
	 * 
	 * @param request
	 * @return
	 */

	@RequiresPermissions("applicationBatch:index")
	@RequestMapping(name = "批次申请主页,applicationBatch:index", value = "/batch", method = { RequestMethod.POST,
			RequestMethod.GET })
	public String Application2(HttpServletRequest request) {
		String root = request.getSession().getServletContext().getRealPath("/");

		DwzPage<Other> dPage = acs.queryApplyBatchListByPage(1, 20,root);
		request.getSession().removeAttribute("dPage");
		request.getSession().setAttribute("dPage", dPage);
		return "ApplicationBatch";
	}

	/**
	 * 导入文件刷新页面
	 * 
	 * @param request
	 * @return
	 */
	@RequiresPermissions("applicationBatch:refresh")
	@RequestMapping(name = "批次申请页面刷新,applicationBatch:refresh", value = "/getFilesByEmport", method = RequestMethod.POST)
	@ResponseBody
	public DwzPage<Other> batchPage(HttpServletRequest request) {
		String root = request.getSession().getServletContext().getRealPath("/");

		DwzPage<Other> dPage = acs.queryApplyBatchListByPage(1, 20,root);// 默认首页20条数据

		return dPage;
	}

	/**
	 * 获取文件集合
	 * 
	 * @param request
	 * @return
	 */
	@RequiresPermissions("applicationBatch:fileList")
	@RequestMapping(name = "批次申请文件集合,applicationBatch:fileList", value = "/getfiles", method = RequestMethod.POST)
	@ResponseBody
	public DwzPage<Other> getFiles(HttpServletRequest request) {
		@SuppressWarnings("unchecked")
		DwzPage<Other> dPage = (DwzPage<Other>) request.getSession().getAttribute("dPage");
		request.getSession().removeAttribute("dPage");
		return dPage;
	}

	/**
	 * 分页
	 * 
	 * @param numPerPage
	 * @return
	 */
	@RequiresPermissions("applicationBatch:page2")
	@RequestMapping(name = "批次申请分页2,applicationBatch:page2", value = "/paging", method = RequestMethod.POST)
	@ResponseBody
	public DwzPage<Other> paging(Integer pageNum, Integer numPerPage, HttpServletRequest request) {
		String root = request.getSession().getServletContext().getRealPath("/");
		
		DwzPage<Other> dPage = acs.queryApplyBatchListByPage(pageNum, numPerPage,root);
		return dPage;
	}

	/**
	 * 导入,并添加批次号状态
	 * 
	 * @param request
	 * @param ids
	 * @param applyBatchNo
	 * @return
	 * @throws Exception
	 */
	@RequiresPermissions("applicationBatch:importBatchFile")
	@RequestMapping(name = "批次申请导入批次文件,applicationBatch:importBatchFile", value = "/emport", method = RequestMethod.POST)
	@ResponseBody
	public Map<String, Object> emportinfo(HttpServletRequest request, String[] ids, String applyBatchNo)
			throws Exception {
		logger.info("emportinfo########start()");
		String root = request.getSession().getServletContext().getRealPath("/");
		Map<String, Object> map = acs.BA(ids,root);
		//VoucherVo vo=(VoucherVo) map.get(Arrays.toString(ids));
		VoucherVo vo=(VoucherVo) map.get(ids[0]);
		//request.getSession().removeAttribute(ids[0]);;
		if(vo != null){
		request.getSession().setAttribute("vo", vo);
		request.getSession().setAttribute("type", "applyBatchRegister");
		map.put("max", "true");
        map.put("title", "批量申领凭证");
        map.put("rel", "applyBatchRegister");
        map.put("statusCode", "200");
        map.put("url", "printCredentials/toHairpinPdfView");
        //20181206 hgl 以下三行
        map.put("jumpToTabid", "ApplicationBatch");
        map.put("jumpToUrl", "applicationBatch/batch");//
        map.put("jumpToTile", "批量申请");
		}
		logger.info("emportinfo########end()");
		return map;
	}

	// 20180131 惠国磊 以下23行 初版
	/**
	 * 导出异常数据文件
	 * 
	 * @param request
	 * @return
	 * @throws Exception
	 */
	@RequiresPermissions("applicationBatch:exportExceptionBatchFile")
	@RequestMapping(name = "批次申请导出异常信息,applicationBatch:exportExceptionBatchFile", value = "/export", method = RequestMethod.POST)
	@ResponseBody
	public Map<String, Object> expot(HttpServletRequest request) throws Exception {

		logger.info("expot########start()");
		String applyBatchNo = request.getParameter("applyBatchNo");
		String[] arr_applyBatchNo = applyBatchNo.split(",");
		for (int i = 0; i < arr_applyBatchNo.length; i++) {
			logger.debug("取得的批次号参数[" + i + "是：" + arr_applyBatchNo[i]);
		}
		String root = request.getSession().getServletContext().getRealPath("/");
		root+="|"+request.getSession().getServletContext().getContextPath();
		Map<String, Object> map = new HashMap<>();
		map.put("st", acs.exportData(arr_applyBatchNo,root));
		
		logger.info("expot########end()");
		return map;

	}

	@RequiresPermissions("applicationBatch:goExportTemplate")
	@RequestMapping(value = "/goExportTemplate", name = "去导出模板页面,applicationBatch:goExportTemplate", method = {
			RequestMethod.POST, RequestMethod.GET })
	public String goExportTemplate() {

		return "ExportFileTemplate";
	}

	@RequiresPermissions("applicationBatch:exportTemplate")
	@RequestMapping(value = "/exportTemplate", name = "导出模板,applicationBatch:exportTemplate", method = RequestMethod.POST)
	@ResponseBody
	public Map<String, Object> exportTemplate(String cardPCode, String cardPhysicalType,HttpServletRequest request) {
		String root =request.getSession().getServletContext().getRealPath("/");
		root+="|"+request.getSession().getServletContext().getContextPath();
		ResultVo vo = pm.exportApplyTemplate(root,cardPCode, cardPhysicalType);
		Map<String, Object> map = new HashMap<>();
		if (vo.getResultStatus().getCode() == (HttpContants.RETURN_SUCCESS)) {
			map.put("statuscode", HttpContants.RETURN_SUCCESS);
			map.put("serviceObject", vo.getServiceObject());
		} else {
			map.put("statuscode", "300");
			map.put("message", vo.getResultStatus().getMessage());
		}
		return map;
	}
	/**
	 * 跳转批量申请收费页面
	 * 
	 * @param request
	 * @return
	 * @throws Exception
	 */
	@RequiresPermissions("applicationBatch:goCharge")
	@RequestMapping(value = "/goCharge", name = "去收费页面,applicationBatch:goCharge", method = {
			RequestMethod.POST, RequestMethod.GET })
	public String goCharge(String param,HttpServletRequest request) {
        request.getSession().setAttribute("param", param);
		return "ChargeBatch";
	}
	/**
	 * 获取收费信息
	 * 
	 * @param request
	 * @return
	 * @throws ApplicationException 
	 * @throws Exception
	 */
	@RequiresPermissions("applicationBatch:getCharge")
	@RequestMapping(value = "/getCharge", name = "获取收费信息,applicationBatch:getCharge", method = RequestMethod.POST)
	@ResponseBody
	public Map<String, Object> getCharge(HttpServletRequest request) throws ApplicationException {
		String root =request.getSession().getServletContext().getRealPath("/");
		root+="/"+PathContants.PROJECT_PATH_EXCEL;
		String applyBatchNo=(String) request.getSession().getAttribute("param");
		request.getSession().removeAttribute("param");
		ShowChargeVo vo = acs.showCharge(root, applyBatchNo);
		Map<String, Object> map = new HashMap<>();
		map.put("statuscode", "200");
		map.put("vo", vo);
		return map;
	}
	/**
	 * 收费
	 * 
	 * @param request
	 * @return
	 * @throws ApplicationException 
	 * @throws Exception
	 */
	@RequiresPermissions("applicationBatch:chargeFee")
	@RequestMapping(value = "/chargeFee", name = "收取费用,applicationBatch:chargeFee", method = RequestMethod.POST)
	@ResponseBody
	public Map<String, Object> chargeFee(ShowChargeVo scv, HttpServletRequest request) throws ApplicationException {
		VoucherVo vo = acs.charge(scv);
		//request.getSession().setAttribute(scv.getApplyBatchNo(), vo);
		Map<String, Object> map = new HashMap<>();
		map.put("statusCode", "200");
		map.put("message", "收费成功");
		map.put("callbackType", "closeCurrent");
		return map;
	}
	/**
	 * 判断是否收费
	 * 
	 * @param request
	 * @return
	 */
	@RequiresPermissions("applicationBatch:getServices")
	@RequestMapping(value = "/getServices", name = "判断是否收费,applicationBatch:getServices", method = RequestMethod.POST)
	@ResponseBody
	public Map<String, Object> getServices(String applyBatchNo){
		System.out.println(""+applyBatchNo);
		int isExist=bm.queryApplyBatchNo(applyBatchNo);
		System.out.println(""+isExist);
		Map<String, Object> map = new HashMap<>();
		if(isExist==0){
			map.put("statusCode", "300");
			map.put("message", "请先收取费用");	
		}
		return map;
	}
}
